package ase.assignment.sts.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ase.assignment.sts.api.HandlerFactoryProxy;
import ase.assignment.sts.api.PortfolioHandler;
import ase.assignment.sts.beans.PortfolioEntity;
import ase.assignment.sts.utils.STSConstants;

public class PortfolioAction extends GenericAction {
	public static final int KEY_SUCCESS = 1;
	public static final int KEY_FAIL = 2;

	public int process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpSession session = request.getSession();
		String sAdd = request.getParameter("add");
		String sDelete = request.getParameter("delete");
		String sPorId = request.getParameter("portfolioId");
		String sPorName = request.getParameter("portfolioName");
		if (sPorId.length() == 0) {
			return KEY_FAIL;
		}
		int iPorId = Integer.parseInt(sPorId);

		PortfolioHandler handler = HandlerFactoryProxy.instance()
				.getPortfolioHandler();
		if (sAdd != null) {
			if (sPorName.length() == 0) {
				return KEY_FAIL;
			}
			try {
				if (handler.findById(iPorId) != null) {
					return KEY_FAIL;
				}
				PortfolioEntity entity = new PortfolioEntity(iPorId);
				entity.setName(sPorName);
				entity.setCustomerName((String) session
						.getAttribute(STSConstants.SESSION_USER));
				handler.create(entity);

				return KEY_SUCCESS;

			} catch (Throwable e) {
				e.printStackTrace();
			}
		} else if (sDelete != null) {
			handler.delete(iPorId);
			return KEY_SUCCESS;
		}
		return KEY_FAIL;
	}
}
